const fs = require("fs");
const { UNKNOWN_ERROR } = require("../config/error-constants");
const userService = require("./../service/user.service");
const { to } = require("./../utils");
const { UPLOAD_FILE_PATH } = require("../config/path");
const fileService = require("../service/file.service");
const { DEFAULT_USER_AVATAR_NAME, DEFAULT_USER_AVATAR_MIMETYPE } = require("../config/file");
const { SERVER_HOST, SERVER_PORT } = require("../config/server");

class UserController {
    async register(ctx, next) {
        // 1.获取用户传递过来的信息
        const params = ctx.request.body;

        // 验证参数逻辑抽离到前一个中间件去了

        // 操作数据库，保存到user表
        // 数据库的操作也比较复杂，抽离到service
        const [error, resp] = await to(userService.register(params));
        // 3.查看存储结果，告知前端创建成功
        ctx.body = {
            message: "创建用户成功~",
            data: resp,
        };
    }

    async getAvatarByUserId(ctx, next) {
        const { userId } = ctx.params;
        const [error, resp] = await to(fileService.getAvatarByUserId(userId));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }
        const { filename = DEFAULT_USER_AVATAR_NAME, mimetype = DEFAULT_USER_AVATAR_MIMETYPE } = resp;
        const readableStream = fs.createReadStream(`${UPLOAD_FILE_PATH}/${filename}`);
        // 设置响应头content-type
        // 否则客户端不能正常显示
        ctx.type = mimetype;
        ctx.body = readableStream;
    }

    async updateUserAvatar(ctx, next) {
        const { id } = ctx.user;
        const avatarUrl = `${SERVER_HOST}:${SERVER_PORT}/users/avatar/${id}`;
        const [error, resp] = await to();
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }
    }

    async updateUserNameOrPassword(ctx, next) {
        const { id } = ctx.user;
        const { name, password } = ctx.request.body;
        const [error, resp] = await to(userService.updateUserNameOrPassword(name, password, id));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }
        ctx.body = {
            code: 0,
            message: "修改用户信息成功~",
        };
    }

    async accountCancellationByUserId(ctx, next) {
        const { userId } = ctx.params;
        const [error, resp] = await to(userService.accountCancellationByUserId(userId));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }
        ctx.body = {
            code: 0,
            message: "注销账户成功，期待再次相遇~",
        };
    }
}

module.exports = new UserController();
